package cn.conac.as.monitor.entity.weixin;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import cn.conac.as.framework.utils.FastJsonUtil;
import cn.conac.as.monitor.constant.WeixinFinalValueType;

@Component
public class RefreshAccessTokenTask {
	public static final String at = "e0-Q2r0PXKdJEwD8yRX_HlPaFCCO5MXBAoBlf7EDoqthtWv7JmRLeKNrFTaeEa7mS8S1-hi78d9zfGemLIFQ-zUNru9W_1HpvdvtJWaS3FcPjAtV4qelQBr_FVe2Y34kXOFhAJAARI";

	public void refreshToken() {
		WeixinContext.setAccessToken(at);
		HttpGet get = null;
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;
		try {
			client = HttpClients.createDefault();
			String url = WeixinFinalValueType.ACCESS_TOKEN_URL;
			url = url.replaceAll("APPID", WeixinFinalValueType.APPID);
			url = url.replaceAll("APPSECRET", WeixinFinalValueType.APPSECRET);
			get = new HttpGet(url);
			resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if(statusCode>=200&&statusCode<300) {
				HttpEntity entity = resp.getEntity();
				String content = EntityUtils.toString(entity);
				try {
//					AccessToken at = (AccessToken) JsonUtil.getInstance().json2obj(content, AccessToken.class);
					AccessToken at = (AccessToken) FastJsonUtil.getObject(content, AccessToken.class);

					WeixinContext.setAccessToken(at.getAccess_token());
					System.out.println("akdkddkdtoken================"+at.getAccess_token()+"----------"+new Date());
				} catch (Exception e) {
//					ErrorEntity err = (ErrorEntity)JsonUtil.getInstance().json2obj(content, ErrorEntity.class);
					ErrorEntity err = (ErrorEntity)FastJsonUtil.getObject(content, ErrorEntity.class);
					System.out.println("获取token异常:"+err.getErrcode()+","+err.getErrmsg());
					refreshToken();
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(resp!=null) resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(client!=null) client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
